package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import net.sf.jsqlparser.statement.IfElseStatement;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * BelongProject: firstProject
 * BelongPackage: com.atguigu.lease.web.admin.custom.converter
 * Description:
 *
 * @Author 段鑫涛
 * @Create 2025/4/25 15:16
 * @Version 1.0
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {

            @Override
            public T convert(String source) {
                T[] enumConstants = targetType.getEnumConstants();
                if(enumConstants != null && enumConstants.length > 0){
                    for (T enumConstant : enumConstants) {
                        if(enumConstant.getCode().equals(Integer.valueOf(source))){
                            return enumConstant;
                        }
                    }
                }
                throw new IllegalArgumentException("非法的枚举值:" + source);
            }
        };
    }
}
